using UnityEngine;
using SomniumSpace.Bridge.Player;

namespace OpenFlight
{
    /// <summary>
    /// Publishes every connected player's foot position to the GPU each frame so
    /// any material using CloudDeform.hlsl can deform around them.
    ///
    /// Player positions are already replicated by Somnium's own avatar sync
    /// (that's how you see other players move at all) -- this script does not
    /// open its own network channel. It just republishes data SomniumBridge
    /// already has as global shader properties, so every client independently
    /// computes the same deformation and every client's clouds match.
    ///
    /// Add ONE instance of this to your scene (e.g. an empty "CloudDeformSystem"
    /// GameObject). Every cloud material anywhere in the scene reads the same
    /// global arrays, so this single feeder drives all of them.
    /// </summary>
    public class CloudDeformFeeder : MonoBehaviour
    {
        // Must match CLOUD_DEFORM_MAX_PLAYERS in CloudDeform.hlsl. If you raise
        // this, raise it in both places.
        private const int MaxTrackedPlayers = 8;

        private static readonly int PositionsId = Shader.PropertyToID("_CloudDeformPlayerPositions");
        private static readonly int CountId = Shader.PropertyToID("_CloudDeformPlayerCount");

        // Sentinel far outside any reasonable world so unused slots never
        // influence a cloud's falloff calculation.
        private static readonly Vector4 Sentinel = new Vector4(100000f, 100000f, 100000f, 0f);

        private readonly Vector4[] _positions = new Vector4[MaxTrackedPlayers];

        private void Update()
        {
            int count = 0;

            var localPlayer = SomniumBridge.PlayersContainer?.LocalPlayer;
            if (localPlayer != null)
            {
                count = TryAdd(localPlayer, count);
            }

            var others = SomniumBridge.PlayersContainer?.AllPlayers;
            if (others != null)
            {
                for (int i = 0; i < others.Count && count < MaxTrackedPlayers; i++)
                {
                    count = TryAdd(others[i], count);
                }
            }

            for (int i = count; i < MaxTrackedPlayers; i++)
            {
                _positions[i] = Sentinel;
            }

            Shader.SetGlobalVectorArray(PositionsId, _positions);
            Shader.SetGlobalInt(CountId, count);
        }

        private int TryAdd(ISomniumPlayer player, int count)
        {
            if (count >= MaxTrackedPlayers) return count;

            // Root = player root/feet transform, per SomniumBridge Player API.
            var root = player?.References?.Body?.Root;
            if (root == null) return count;

            Vector3 pos = root.position;
            _positions[count] = new Vector4(pos.x, pos.y, pos.z, 0f);
            return count + 1;
        }
    }
}
